#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
视频控制模块
负责处理视频播放控制相关功能，如跳转、步进等操作
"""

import cv2
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox, QFileDialog, QProgressDialog, QApplication

# 导入项目模块
from src.video.segment_manager import SegmentType


class VideoControls:
    """视频控制器类"""

    def __init__(self):
        """初始化视频控制器"""
        pass

    def skip_to_start(self, main_window):
        """跳转到视频开始"""
        if main_window.cap:
            main_window.current_time = 0.0
            main_window.cap.set(cv2.CAP_PROP_POS_MSEC, 0)
            main_window.progress_slider.setValue(0)
            main_window.show_frame_at_time(0.0)
            
            # 更新时间显示
            if main_window.video_processor.get_video_info():
                duration = main_window.video_processor.get_video_duration()
                main_window.update_time_display(0.0, duration)

    def step_backward(self, main_window):
        """后退一帧"""
        if main_window.cap and main_window.video_processor.get_video_info():
            fps = main_window.video_processor.get_video_info().get('fps', 30)
            frame_time = 1.0 / fps
            
            main_window.current_time = max(0.0, main_window.current_time - frame_time)
            main_window.show_frame_at_time(main_window.current_time)
            
            # 更新滑块位置
            duration = main_window.video_processor.get_video_duration()
            if duration > 0:
                slider_value = int((main_window.current_time / duration) * 1000)
                main_window.progress_slider.setValue(slider_value)
                
            # 更新时间显示
            main_window.update_time_display(main_window.current_time, duration)

    def step_forward(self, main_window):
        """前进一帧"""
        if main_window.cap and main_window.video_processor.get_video_info():
            fps = main_window.video_processor.get_video_info().get('fps', 30)
            frame_time = 1.0 / fps
            duration = main_window.video_processor.get_video_duration()
            
            main_window.current_time = min(duration, main_window.current_time + frame_time)
            main_window.show_frame_at_time(main_window.current_time)
            
            # 更新滑块位置
            if duration > 0:
                slider_value = int((main_window.current_time / duration) * 1000)
                main_window.progress_slider.setValue(slider_value)
                
            # 更新时间显示
            main_window.update_time_display(main_window.current_time, duration)

    def skip_to_end(self, main_window):
        """跳转到视频结束"""
        if main_window.cap and main_window.video_processor.get_video_info():
            duration = main_window.video_processor.get_video_duration()
            main_window.current_time = duration
            main_window.show_frame_at_time(duration)
            
            # 更新滑块位置
            main_window.progress_slider.setValue(1000)
            
            # 更新时间显示
            main_window.update_time_display(duration, duration)

    def mark_in_point(self, main_window):
        """标记入点"""
        main_window.segment_manager.mark_start(main_window.current_time)
        mode_text = "保留" if main_window.segment_manager.current_mode == SegmentType.KEEP else "删除"
        QMessageBox.information(main_window, "标记", f"已在 {main_window.format_time(main_window.current_time)} 标记入点（模式：{mode_text}）")

    def mark_out_point(self, main_window):
        """标记出点"""
        success = main_window.segment_manager.mark_end(main_window.current_time)
        if success:
            mode_text = "保留" if main_window.segment_manager.current_mode == SegmentType.KEEP else "删除"
            QMessageBox.information(main_window, "标记", f"已在 {main_window.format_time(main_window.current_time)} 标记出点（模式：{mode_text}）")
            # 更新片段列表显示
            main_window.update_segment_list()
        else:
            QMessageBox.warning(main_window, "标记错误", "请先标记入点，且出点时间必须大于入点时间")

    def export_video(self, main_window):
        """导出视频"""
        if not main_window.video_processor.video_path:
            QMessageBox.warning(main_window, "导出视频", "请先导入视频文件")
            return
            
        # 获取保留片段
        segments = main_window.segment_manager.get_final_segments()
        
        if not segments:
            QMessageBox.warning(main_window, "导出视频", "没有标记任何保留片段，请先标记要保留的片段")
            return
            
        # 选择输出文件路径
        output_path, _ = QFileDialog.getSaveFileName(
            main_window, "保存视频文件", "", 
            "视频文件 (*.mp4 *.mov *.avi)"
        )
        
        if not output_path:
            return
            
        # 创建进度对话框
        progress_dialog = QProgressDialog("正在导出视频...", "取消", 0, 100, main_window)
        progress_dialog.setWindowModality(Qt.WindowModal)
        progress_dialog.setWindowTitle("导出进度")
        progress_dialog.show()
        
        # 定义进度回调函数
        def progress_callback(progress):
            progress_dialog.setValue(progress)
            QApplication.processEvents()  # 处理GUI事件
            
            if progress_dialog.wasCanceled():
                return False
            return True
        
        # 执行导出
        try:
            success = main_window.video_exporter.export_video(
                main_window.video_processor.video_path,
                main_window.segment_manager.get_segments(),
                output_path,
                progress_callback
            )
            
            progress_dialog.close()
            
            if success:
                QMessageBox.information(main_window, "导出成功", f"视频已成功导出到:\n{output_path}")
            else:
                QMessageBox.critical(main_window, "导出失败", "视频导出失败，请查看控制台错误信息")
                
        except Exception as e:
            progress_dialog.close()
            QMessageBox.critical(main_window, "导出错误", f"导出过程中发生错误:\n{str(e)}")

    def delete_selected_segment(self, main_window):
        """删除选中的片段"""
        current_row = main_window.segment_list_widget.currentRow()
        if current_row >= 0:
            reply = QMessageBox.question(main_window, "确认删除", "确定要删除选中的片段吗？",
                                       QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                main_window.segment_manager.remove_segment(current_row)
                main_window.update_segment_list()
        else:
            QMessageBox.warning(main_window, "删除片段", "请先选择要删除的片段")

    def clear_all_segments(self, main_window):
        """清空所有片段"""
        if main_window.segment_manager.get_segments():
            reply = QMessageBox.question(main_window, "确认清空", "确定要清空所有片段吗？",
                                       QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                main_window.segment_manager.clear_segments()
                main_window.update_segment_list()
        else:
            QMessageBox.information(main_window, "清空片段", "当前没有标记任何片段")